package org.happy.tester.catcher.util;

import com.alibaba.fastjson.JSONObject;
import com.offbytwo.jenkins.JenkinsTriggerHelper;
import com.offbytwo.jenkins.model.BuildResult;
import com.offbytwo.jenkins.model.BuildWithDetails;
import org.happy.tester.common.http.req.PointcutRequest;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname JenkinsUtil
 * @Description TODO
 * @Date 2020/6/30 10:22 下午
 * @Created by jc.bai
 */
@Component
public class JenkinsUtil {

    @Resource
    private JenkinsTriggerHelper jenkinsTriggerHelper;

    public boolean deployAgentLoader(PointcutRequest pointcutRequest) throws IOException, InterruptedException {
        if (!deployAgent()) {
            return false;
        }
        Map<String, String> paramMap = new HashMap<>();
        String pointcutList = JSONObject.toJSONString(pointcutRequest);
        paramMap.put("pointcutList", pointcutList);
        BuildWithDetails details = jenkinsTriggerHelper.triggerJobAndWaitUntilFinished("loadAgent", paramMap, true);
        BuildResult result = details.getResult();
        if (result.equals(BuildResult.SUCCESS)) {
            return true;
        }
        return false;
    }

    private boolean deployAgent() throws IOException, InterruptedException {
        BuildWithDetails pushAgent = jenkinsTriggerHelper.triggerJobAndWaitUntilFinished("pushAgent", true);
        if (pushAgent.getResult().equals(BuildResult.SUCCESS)) {
            return true;
        }
        return false;
    }
}
